package top.blueShark.template.common.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 工具类：File转MultipartFile
 */
public class FileMultipartFileUtil {
    /**
     * 将File对象转换为Spring的MultipartFile
     * @param file 源文件
     * @return MultipartFile
     * @throws IOException IO异常
     */
    public static MultipartFile fileToMultipartFile(File file) throws IOException {
        return new SimpleMultipartFile(file);
    }

    /**
     * 简单实现MultipartFile，适用于本地File转MultipartFile
     */
    public static class SimpleMultipartFile implements MultipartFile {
        private final File file;
        private final byte[] content;

        public SimpleMultipartFile(File file) throws IOException {
            this.file = file;
            try (FileInputStream fis = new FileInputStream(file)) {
                this.content = fis.readAllBytes();
            }
        }

        @Override
        public String getName() {
            return file.getName();
        }

        @Override
        public String getOriginalFilename() {
            return file.getName();
        }

        @Override
        public String getContentType() {
            return null;
        }

        @Override
        public boolean isEmpty() {
            return content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new java.io.ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            try (java.io.FileOutputStream fos = new java.io.FileOutputStream(dest)) {
                fos.write(content);
            }
        }
    }

    /**
     * 从网络URL下载文件到本地临时文件
     * @param urlStr 文件URL
     * @return 本地临时File对象
     * @throws IOException IO异常
     */
    public static File downloadUrlToFile(String urlStr) throws IOException {
        java.net.URL url = new java.net.URL(urlStr);
        File tempFile = File.createTempFile("download_", ".tmp");
        tempFile.deleteOnExit();
        try (InputStream in = url.openStream();
             java.io.OutputStream out = new java.io.FileOutputStream(tempFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    }
} 